<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String invoice_type = request.getParameter("invoice_type") == null ? "0" : request.getParameter("invoice_type");
	String xm_id = request.getParameter("xm_id") == null ? "" : request.getParameter("xm_id");
	String dept_id = request.getParameter("dept_id") == null ? "" : request.getParameter("dept_id");
	String dept = request.getParameter("dept_name") == null ? "" : request.getParameter("dept_name");
	String xm_code = request.getParameter("xm_code") == null ? "" : request.getParameter("xm_code");
	String xm_name = request.getParameter("xm_name") == null ? "" : request.getParameter("xm_name");
	String customer_id = request.getParameter("customer_id") == null ? "" : request.getParameter("customer_id");
	String customer = request.getParameter("customer") == null ? "" : request.getParameter("customer");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建项目开票":"编辑项目开票" %></title>
		<script type="text/javascript" src="<%=contextPath %>/public/js/extend.js"></script>
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
		</style>
	<script type="text/javascript">
		var lastIndex;
		var dept_id; 
		$(function(){;
			$('#invoice_type').val('<%=invoice_type%>');
			if('<%=flag%>' == 1){
				jQuery('#ff').form({
				onLoadSuccess:function(){
				     jQuery('#person').val(jQuery('#creator').val());
				     jQuery.ajax({
					    	type:'POST',
					    	url:'<%=contextPath %>/springMVC/xm/getAlreadyOutInvoice?xm_id='+jQuery('#xm_id').val(),
					    	success:function(rtJson){
					    		jQuery("#already_out_invoice").numberbox('setValue',rtJson);
					    	}
					    });
				}
			});
		   jQuery('#ff').form('load','<%=contextPath%>/springMVC/xmFinance/getXMInvoiceById?id=<%=id%>');

			}
	       $('#table').datagrid({
	         	url:contextPath+"/springMVC/xmFinance/getXMInvoiceDetail?id=<%=request.getParameter("id")%>",
				rownumbers:true,
				fitColumns:true,
				frozenColumns:[[
					{field:'ck',checkbox:true},
				    {title:'分包商id',field:'worker_id',hidden:true}
				]],
				columns:[[
					{title:'分包商名称',field:'worker_company',width:250,align:'center',editor:{
						type:'combogrid',
						options:{
							url: '<%=contextPath %>/springMVC/xm/listPageWorker',
						    panelWidth:750,
						    panelHeight:355,
						    rownumbers:true,
						    onBeforeLoad:function(param){
						    	param.xm_id = jQuery('#xm_id').val();
						    },
						    fitColumns:true,
						    columns: [[  
						       {field:'id',title:'主键',hidden:true},  
						       {field:'worker_company',title:'分包商',width:200,align:'center'},
						       {field:'type_id',title:'类型',width:200,align:'center',formatter:function(value,rowData,rowIndex){
									if(value==0){
										return "内部班组";
									}else if(value==1){
										return "外部施工队";
									}
									return "未知";
								}},
						       {field:'worker_person',title:'负责人',width:100,align:'center'},
						       {field:'contact',title:'联系方式',width:150,align:'center'}
						    ]],
						    pageList : [10,50,100],  
							pagination:true,
							onClickRow:function(rowIndex,rowData){
								if(checkSameWorker(rowData,$('#table').datagrid('getData').rows)){
									var pRow = $('#table').datagrid('getRows')[lastIndex];
									pRow.worker_id = rowData.id;
									pRow.worker_company = rowData.worker_company;
									pRow.worker_person = rowData.worker_person;
									$('#table').datagrid('getData').rows[lastIndex]=pRow;
									var data = $('#table').datagrid('getData');
									$('#table').datagrid('loadData',data);
									
									$('#table').datagrid('endEdit', lastIndex);
									$('#table').datagrid('beginEdit', lastIndex);
									
									//lastIndex =-1;
								}else{
									$.messager.alert("提示","选择的分包商已经存在");
								}
							}
						}
					}},
					{title:'负责人',field:'worker_person',width:150,align:'center'},
					{title:'开票额(元)',field:'out_invoice',width:200,align:'center',
						editor:{
							type:'numberbox',
							options:{
								 min:0,    
	    						 precision:2 
							}
					}},
					{title:'税金(元)',field:'tax',hidden:true,align:'center',editor:{
						type:'numberbox',
						options:{
							precision:2
						}
					}},
					{title:'备注',field:'remark',width:200,align:'center',editor:{
						type:'textarea'
					}}
				]],
				onBeforeLoad:function(){
					$(this).datagrid('rejectChanges');
				},
				onLoadSuccess:function(data){
				<%if(flag==1){%>
					calTax();
					<%}%>
				},
				onClickCell:function(rowIndex,field,value){
					if (lastIndex != rowIndex){
						$('#table').datagrid('endEdit', lastIndex);
						$('#table').datagrid('beginEdit', rowIndex);
						var ed = $('#table').datagrid('getEditor', {index:rowIndex,field:field});
						if(ed == null){
							ed = $('#table').datagrid('getEditor', {index:rowIndex,field:'out_invoice'});
						}
						$(ed.target).select();
					}
					lastIndex = rowIndex;
				},
				toolbar:[
					{
						id:'add',
						text:'选择分包商',
						disabled:false,
						iconCls:'icon-add',
						handler:function(){
							addRow();
						}
					},'-',{
					id:'save',
					text:'保存修改',
					disabled:false,
					iconCls:'icon-save',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
						acountTax();
					}
					},'-',{
					id:'delete',
					text:'删除',
					disabled:false,
					iconCls:'icon-remove',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
						var rows = $('#table').datagrid('getSelections');
						if (rows.length > 0){
							for(var i=0;i<rows.length;i++){
								var row = rows[i];
								var index = $('#table').datagrid('getRowIndex', row);
								$('#table').datagrid('deleteRow', index);
							}
						}
						var data = $('#table').datagrid('getData');
						$('#table').datagrid('loadData',data);
					}
				}
			   ]
			});
			
		});
		
		function checkSameWorker(rowData,rows){
			if (rows.length > 0){
				for(var i=0;i<rows.length;i++){
					if(rows[i].worker_id==rowData.id){
						return false;
					}
				}
			}
			return true;
		}
		function acountTax(){
			var jsondata=$("#table").datagrid("getData");
			var workers_out_invoice=0;
			for(var i=0;i<jsondata.total;i++){
				var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
				if(jsondata.rows[i].worker_company == null || jsondata.rows[i].worker_company == ""){
					$.messager.alert('提示','第'+index+'行未选择产品！');
					return ;
				}else if(jsondata.rows[i].out_invoice == null || jsondata.rows[i].out_invoice < 0){
					$.messager.alert('提示','第'+index+'行数量填写不正确！');
					return ;
				}
				else{
					workers_out_invoice=parseFloat(workers_out_invoice)+parseFloat(jsondata.rows[i].out_invoice);
				}
			}
			var account_receivable=jQuery("#account_receivable").numberbox('getValue');
			var tax_rate=jQuery("#tax_rate").val();
			var tax = Math.round(((parseFloat(account_receivable)-parseFloat(workers_out_invoice))*parseFloat(tax_rate))*Math.pow(10,2))/Math.pow(10,2);
			jQuery('#company_tax').numberbox('setValue',tax);
		}
		function calTax(){
			var jsondata=$("#table").datagrid("getData");
			var workers_out_invoice=0;
			for(var i=0;i<jsondata.total;i++){
				if(jsondata.rows[i].out_invoice == null || jsondata.rows[i].out_invoice == ""){
					continue;
				}
				workers_out_invoice=parseFloat(workers_out_invoice)+parseFloat(jsondata.rows[i].out_invoice);
			}
			var account_receivable=jQuery("#account_receivable").val();
			var company_tax=jQuery("#company_tax").val();
			var tax_rate=((parseFloat(company_tax)/(parseFloat(account_receivable)-parseFloat(workers_out_invoice))));
			jQuery("#tax_rate").numberbox('setValue',tax_rate);
		}
		function addRow(){
			if(jQuery('#xm_id').val() == null || jQuery('#xm_id').val()==''){
				$.messager.alert('提示','请先选择项目');
				return;
			}
			$('#table').datagrid('endEdit', lastIndex);
			$('#table').datagrid('appendRow',{
			});
			var data = $('#table').datagrid('getData');
			$('#table').datagrid('loadData',data);
			lastIndex = $('#table').datagrid('getRows').length-1;
			$('#table').datagrid('selectRow', lastIndex);
			$('#table').datagrid('beginEdit', lastIndex);
		}
		
		function addXMInvoiceRequest(obj){
			//自动提交数据
			$('#table').datagrid('acceptChanges');
			lastIndex =-1;
			//自动提交数据
			var xm_id =jQuery("#xm_id").val();	
			var xm_name=jQuery("#xm_name").val();	
			var xm_code=jQuery("#xm_code").val();
			var invoice_title=encodeURIComponent(jQuery("#invoice_title").val());
			var remark=encodeURIComponent(jQuery('#remark').val());
			if(!checkNullOREmpty(xm_id,'项目为必填项')){return;}
			if(!checkNullOREmpty(invoice_title,'抬头为必填项')){return;}
			var customer_id =jQuery("#customer_id").val();		
			var invoice_type =jQuery("#invoice_type").val();		
			var dept =jQuery("#dept_name").val();	
			var customer =jQuery("#customer").val();	
			var account_receivable=jQuery("#account_receivable").numberbox('getValue');
			var company_out_invoice = 0;
			var alarm_time=jQuery("#alarm_time").datebox('getValue');
			var warranty_value=jQuery("#warranty_value").numberbox('getValue');
			var warranty_alarm_time=jQuery("#warranty_alarm_time").datebox('getValue');
			var workers="";
			var jsondata=$("#table").datagrid("getData");
			var workers_out_invoice=0;
			for(var i=0;i<jsondata.total;i++){
				if(workers!=""){
					workers+=";";
				}
				workers+=jsonToStr(jsondata.rows[i]);
				var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
				if(jsondata.rows[i].worker_company == null || jsondata.rows[i].worker_company == ""){
					$.messager.alert('提示','第'+index+'行未选择产品！');
					return ;
				}else if(jsondata.rows[i].out_invoice == null || jsondata.rows[i].out_invoice < 0){
					$.messager.alert('提示','第'+index+'行数量填写不正确！');
					return ;
				}
				else{
					workers_out_invoice=parseFloat(workers_out_invoice)+parseFloat(jsondata.rows[i].out_invoice);
					
				}
			}
		    if(parseFloat(workers_out_invoice) > parseFloat(account_receivable)){
		    	$.messager.alert('提示','分包商总金额不能大于开票总额！');
				return ;
		    }
		    if(parseFloat(warranty_value) > parseFloat(account_receivable)){
		    	$.messager.alert('提示','质保金不能大于开票总额！');
				return ;
		    }
		    var account_receivable=jQuery("#account_receivable").numberbox('getValue');
		    var tax_rate=jQuery("#tax_rate").val();
			var company_tax = jQuery("#company_tax").numberbox('getValue');
		    
			var param = "warranty_value="+warranty_value+"&warranty_alarm_time="+warranty_alarm_time+"&customer_id="+customer_id+"&customer="+customer+"&remark="+remark
			+"&invoice_title="+invoice_title+"&account_receivable="+account_receivable+"&company_out_invoice="+company_out_invoice
			+"&company_tax="+company_tax+"&alarm_time="+alarm_time+"&invoice_type="+invoice_type
			+"&xm_id="+xm_id+"&xm_code="+xm_code+"&xm_name="+xm_name+"&dept_id="+dept_id+"&dept="+dept+"&workers="+workers;
			$(obj).hide();
			$.ajax({
				type:'POST',
				<%=isAdd?"url:'"+contextPath+"/springMVC/xmFinance/addXMEndInvoice',":"url:'"+contextPath+"/springMVC/xmFinance/updateXMEndInvoice?id="+id+"',"%>
				data:param,
				dataType:'json',
				success:function(rtJson){
					if(rtJson.rtState == '0'){
						eval('window.opener.<%=callback%>();');
						window.close();
					}
					else{
						$.messager.alert("提示",rtJson.rtMsrg);
					}
					$(obj).show();
				}
			});
		}
		function choseXm(){
				<%if("0".equals(invoice_type)){%>
				//验收后停止进度开票
		    	openDialogResize("<%=contextPath %>/springViews/xm/choseMyXM.jsp?statusType=4",1000, 800);
				<%}%>
				<%if("1".equals(invoice_type)){%>
		    	openDialogResize("<%=contextPath %>/springViews/xm/choseMyXMEnd.jsp",1000, 800);
				<%}%>
		}
		function rtCallBackXmSet(xm_id,xm_code,xm_name,deptId,dept,customer_id,customer){
		    dept_id=deptId;
			jQuery("#xm_id").val(xm_id);
		    jQuery("#xm_name").val(xm_name);
		    jQuery("#xm_code").val(xm_code);
		    jQuery("#dept_name").val(dept);
		    jQuery("#dept_id").val(dept_id);
		    jQuery("#customer_id").val(customer_id);
		    jQuery("#customer").val(customer);
		    jQuery("#invoice_title").val(customer);
		    jQuery.ajax({
		    	type:'POST',
		    	url:'<%=contextPath %>/springMVC/xm/getAlreadyOutInvoice?xm_id='+xm_id,
		    	success:function(rtJson){
		    		jQuery("#already_out_invoice").numberbox('setValue',rtJson);
		    	}
		    });
		}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="ff">
		<input type="hidden" id="creator" name="creator"/>
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>
					<td align="right" class="td1" nowrap>项目编号：</td>
					<td class="td2" nowrap>
					<%if("0".equals(invoice_type)){%>
						<input  id="xm_code" name="xm_code" readOnly value="<%=xm_code%>" placeholder="项目验收后停止进度开票">
					<%}else if("1".equals(invoice_type)){%>
						<input  id="xm_code" name="xm_code" readOnly value="<%=xm_code%>" placeholder="项目送审后才能结算开票">
					<%}%>
						<input type="hidden" id="xm_id" name="xm_id" readOnly value="<%=xm_id%>">
						<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:false" onclick="choseXm();"></a>								</td>
	
					</td>
					<td align="right" class="td1" nowrap>项目名称：</td>
					<td class="td2" nowrap>
					<%if("0".equals(invoice_type)){%>
						<input  id="xm_name" name="xm_name" readOnly value="<%=xm_name%>" placeholder="项目验收后停止进度开票">
					<%}else if("1".equals(invoice_type)){%>
						<input  id="xm_name" name="xm_name" readOnly value="<%=xm_name%>" placeholder="项目送审后才能结算开票">
					<%}%>
						
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>项目部门：</td>
					<td class="td2" nowrap>
						<input  id="dept_name" name="dept_name" readOnly value="<%=dept%>">
						<input  type="hidden" id="dept_id" name="dept_id" readOnly value="<%=dept_id%>">
					</td>
					<td align="right" class="td1" nowrap>经办人：</td>
					<td class="td2" nowrap>
						<input  id="person" name="person" readOnly value="<%=person%>">
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>对应客户：</td>
					<td class="td2" nowrap>
						<input  id="customer" name="customer" readOnly value="<%=customer%>">
						<input  type="hidden" id="customer_id" name="customer_id" readOnly value="<%=customer_id%>">
					</td>
					<td align="right" class="td1" nowrap>开票类型：</td>
					<td class="td2" nowrap>
						<select id="invoice_type" name="invoice_type" disabled="disabled"">
							<option value="0">进度开票</option>
							<option value="1">结算开票</option>
						</select>
					</td>
				</tr>
				<tr>
			        <td align="right" class="td1" nowrap>发票抬头：</td>
					<td class="td2" nowrap colspan="3">
						<input  id="invoice_title" style="width:90%"  name="invoice_title">
					</td>
				</tr>
				<tr>	
			        <td align="right" class="td1" nowrap>已开票额：</td>
					<td class="td2" nowrap>
						<input  id="already_out_invoice" name="already_out_invoice" class="easyui-numberbox" data-options="disabled:true">
					</td>
			        <td align="right" class="td1" nowrap>本次开票额：</td>
					<td class="td2" nowrap>
						<input  id="account_receivable" name="account_receivable" class="easyui-numberbox" data-options="min:0,precision:2" value="0">
					</td>
				<tr>
				<tr>
			       <td align="right" class="td1" nowrap>调整税率：</td>
					<td class="td2" colspan="3" nowrap>
						<input  id="tax_rate" name="tax_rate" class="easyui-numberbox"   data-options="disabled:false,precision:5"><a href="javascript:acountTax()">计算税金</a>(默认税率为0.0339,可以自行调整)。
					</td>
				    	
				</tr>
				<tr>
			       <td align="right" class="td1" nowrap>税金：</td>
					<td class="td2" nowrap>
						<input  id="company_tax" name="company_tax" class="easyui-numberbox" data-options="disabled:false,precision:2">
					</td>
				    <td align="right" class="td1" nowrap>收款提醒时间：</td>
					<td class="td2" nowrap >
						<input  id="alarm_time" name="alarm_time" class="easyui-datebox"/>
					</td>		
				</tr>
				<tr>
			       <td align="right" class="td1" nowrap>质保金：</td>
					<td class="td2" nowrap>
						<input  id="warranty_value" name="warranty_value" class="easyui-numberbox" data-options="min:0,precision:2" value="0">
					</td>
				    <td align="right" class="td1" nowrap>质保金提醒时间：</td>
					<td class="td2" nowrap >
						<input  id="warranty_alarm_time" name="warranty_alarm_time" class="easyui-datebox"/>
					</td>		
				</tr>
				<tr style="display:none;">
					<td align="right" class="td1" nowrap>公司承担金额：</td>
					<td class="td2" nowrap>
						<input  id="company_out_invoice" name="company_out_invoice"  class="easyui-numberbox" data-options="min:0,precision:2" value="0">
					</td>
		      	</tr>
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2" nowrap colspan='3'>
						<textarea  id="remark" name="remark" rows="6" style="width: 100%"></textarea>
					</td>
				</tr>
				<%if(!"1".equals(isShow)){ %>
				<tr>
					<td align="right" class="td1" nowrap></td>
					<td class="td2" nowrap colspan='3'>
						<div align="left">
						   
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="addXMInvoiceRequest(this);">提交</a>
							
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:window.close();">关闭</a>
						</div>
					</td>
				</tr>
				<%} %>
				<tr>
					<td colspan="4"  nowrap>
						<div id="myMsg" style="color:red">*以下选项在审核通过后，会自动在收票管理中增加收票记录。</div>
					</td>
				</tr>			
				<tr>
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
		
	</body>
</html>